package comm.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.log4j.Logger;
import org.json.JSONObject;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ssu.judea.travlog.controller.WebServlet;
import com.ssu.judea.travlog.vo.Member;


import statics.TravlogVars;
import twitter4j.GeoLocation;
import twitter4j.IDs;
import twitter4j.Paging;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.User;
import twitter4j.conf.Configuration;
import twitter4j.http.AccessToken;
import twitter4j.http.Authorization;
import twitter4j.http.OAuthAuthorization;
import twitter4j.http.RequestToken;

public class TwitterAPI {
	
	private Logger logger = Logger.getLogger(TwitterAPI.class);
	
	private SqlMapClient sqlMapper = SqlMapLoader.getInstance();
	
	public Member regMember(HttpServletRequest request,HttpServletResponse response) throws ParserConfigurationException, IOException, SQLException{
		Member result = null;
		
		TravlogHashMap hm = new TravlogHashMap();
		hm = RequestManager.getRequest(request);
		
		
		Twitter twitter = new TwitterFactory().getInstance();
	    twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
	    
		AccessToken at = null;
		try {
			RequestToken rt = new RequestToken(request.getSession().getAttribute("TWITTER_TOKEN").toString(), request.getSession().getAttribute("TWITTER_TOKEN_SECRET").toString());
			at = twitter.getOAuthAccessToken(rt, hm.get("OAUTH_VERIFIER").toString());
			
		} catch (TwitterException e1) {
			e1.printStackTrace();
			return result;
		}
		request.getSession().removeAttribute("TWITTER_TOKEN");
		request.getSession().removeAttribute("TWITTER_TOKEN_SECRET");
		
		twitter.setOAuthAccessToken(at);
		
		User user = null;
		try {
			user = twitter.verifyCredentials();
		} catch (TwitterException e) {
			e.printStackTrace();
			return result;
		}
		
		if(user!=null){
			logger.debug("인증 성공!");
			Member member = new Member();
			member.setTwitterid(user.getScreenName());
			member.setTwitternumber(String.valueOf(user.getId()));
			member.setTwitterpasskey(at.getToken()+"@"+at.getTokenSecret());
			
			request.getSession().setAttribute("MEMBER_PASSKEY", member.getTwitterpasskey());
			
			member.setNick(user.getScreenName());
			member.setProfileurl(user.getProfileImageURL().toString());
			
			int resultUpdate = sqlMapper.update("member.updateMember", member);
			
			//기존에 없다면 Insert!
			if(resultUpdate==0)sqlMapper.insert("member.regMember", member);
			
			Member saveMem = (Member)sqlMapper.queryForObject("member.getMemberById",member.getTwitterid());
			member.setMemberseq(saveMem.getMemberseq());
			
			result = member;
		}
		return result;
	}
	
	public Member regMemberFromMobile(HttpServletRequest request,HttpServletResponse response) throws ParserConfigurationException, IOException, SQLException{
		Member result = null;
		
		TravlogHashMap hm = new TravlogHashMap();
		hm = RequestManager.getRequest(request);
		
		
		Twitter twitter = new TwitterFactory().getInstance();
	    twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
	    
		AccessToken at = null;
		try {
			RequestToken rt = new RequestToken(hm.get("OAUTH_TOKEN").toString(), request.getSession().getAttribute("TWITTER_TOKEN_SECRET").toString());
			at = twitter.getOAuthAccessToken(rt, hm.get("OAUTH_VERIFIER").toString());
			
		} catch (TwitterException e1) {
			e1.printStackTrace();
			return result;
		}
		request.getSession().removeAttribute("TWITTER_TOKEN");
		request.getSession().removeAttribute("TWITTER_TOKEN_SECRET");
		
		twitter.setOAuthAccessToken(at);
		
		User user = null;
		try {
			user = twitter.verifyCredentials();
		} catch (TwitterException e) {
			e.printStackTrace();
			return result;
		}
		
		if(user!=null){
			logger.debug("인증 성공!");
			Member member = new Member();
			member.setTwitterid(user.getScreenName());
			member.setTwitternumber(String.valueOf(user.getId()));
			member.setTwitterpasskey(at.getToken()+"@"+at.getTokenSecret());
			
			request.getSession().setAttribute("MEMBER_PASSKEY", member.getTwitterpasskey());
			
			member.setNick(user.getScreenName());
			member.setProfileurl(user.getProfileImageURL().toString());
			
			logger.debug("인증 성공했을때 클라이언트 세션 ID:"+request.getSession().getAttribute("CURRENT_SESSION"));
			if(request.getSession().getAttribute("CURRENT_SESSION")!=null)
				member.setSession(request.getSession().getAttribute("CURRENT_SESSION").toString());
			
			int resultUpdate = sqlMapper.update("member.updateMember", member);
			
			//기존에 없다면 Insert!
			if(resultUpdate==0)sqlMapper.insert("member.regMember", member);
			
			Member saveMem = (Member)sqlMapper.queryForObject("member.getMemberById",member.getTwitterid());
			member.setMemberseq(saveMem.getMemberseq());
			
			result = member;
		}
		return result;
	}
	
	
	
	public JSONObject getMemberInfoBySeq(String memberSeq){
		try {
			return new JSONObject( ((TravlogHashMap)sqlMapper.queryForObject("member.getMemberBySeq",memberSeq))) ;
		} catch (SQLException e) {
			return null;
		}
	}
	
	public void toAuthPage(HttpServletRequest request,HttpServletResponse response){
		
		Twitter twit = new TwitterFactory().getInstance();
		twit.setOAuthConsumer(TravlogVars.twitterConsumerKey,TravlogVars.twitterConsumersecret);
		String returnUrl = "http://"+request.getServerName()+request.getContextPath()+"/a.trav?action=callback";
		
		RequestToken requestToken = null;
		try {
			requestToken = twit.getOAuthRequestToken(returnUrl);
		} catch (TwitterException e1) {
			e1.printStackTrace();
		}
		
		request.getSession().setAttribute("TWITTER_TOKEN_SECRET",requestToken.getTokenSecret());
		request.getSession().setAttribute("TWITTER_TOKEN", requestToken.getToken());
		try {
			response.sendRedirect(requestToken.getAuthorizationURL());
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}		
		
	}
	
	public void toAuthMobilePage(HttpServletRequest request,HttpServletResponse response){
		
		Twitter twit = new TwitterFactory().getInstance();
		twit.setOAuthConsumer(TravlogVars.twitterConsumerKey,TravlogVars.twitterConsumersecret);
		String returnUrl = "http://"+request.getServerName()+request.getContextPath()+"/auth.m?action=callback";
		
		RequestToken requestToken = null;
		try {
			requestToken = twit.getOAuthRequestToken(returnUrl);
		} catch (TwitterException e1) {
		}
		
		if(requestToken!=null){
			logger.debug("toAuthMobilePage Session수:"+request.getSession().getValueNames().length);
			request.getSession().setAttribute("TWITTER_TOKEN_SECRET",requestToken.getTokenSecret());
			request.getSession().setAttribute("TWITTER_TOKEN", requestToken.getToken());
			if(request.getParameter("session")!=null)
				request.getSession().setAttribute("CURRENT_SESSION",request.getParameter("session").toString());
			logger.debug("toAuthMobilePage Session수:"+request.getSession().getValueNames().length+" TOKEN:"+requestToken.getToken()+"//"+request.getSession().getAttribute("TWITTER_TOKEN"));
			try {
				response.sendRedirect("http://"+request.getServerName()+request.getContextPath()
						+"/auth.m?action=toTwitter&secret="+requestToken.getTokenSecret()
						+"&url="+URLEncoder.encode(requestToken.getAuthorizationURL(),"UTF-8"));
			} catch (IOException e1) {
			}
		}
		try {
			response.getWriter().write("Twitter is no responding...T_T..");
			response.getWriter().write("<div class='error'><img src='http://s.twimg.com/images/whale_error.gif' /></div>");
					
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public String writeTwit(String tokenPare,String content){
		String result = "ERROR";
		Twitter twitter = new TwitterFactory().getInstance();
		try {
			twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
			
			String accessToken = tokenPare.substring(0, tokenPare.indexOf("@"));
			String accessTokenSecret = tokenPare.substring(tokenPare.indexOf("@")+1);
			AccessToken at = new AccessToken(accessToken,accessTokenSecret);
			twitter.setOAuthAccessToken(at);
			if(content.length()>120){
				content = content.substring(0, 119)+"...";
			}
			
			result = twitter.updateStatus(content).getText();
			
			if(result.equals(content)){
				
				result = TravlogVars.SUCCESS;
			}
			System.out.println("@@@@@@@@@@트위터 포스팅 결과:@@@@"+result);
			

		}  catch (TwitterException e) {
			return result;
		}
		
		return result;
	}
	
	public String writeTwit(String tokenPare,String content, double latitude, double longitude){
		String result = "ERROR";
		Twitter twitter = new TwitterFactory().getInstance();
		try {
			twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
			
			String accessToken = tokenPare.substring(0, tokenPare.indexOf("@"));
			String accessTokenSecret = tokenPare.substring(tokenPare.indexOf("@")+1);
			AccessToken at = new AccessToken(accessToken,accessTokenSecret);
			twitter.setOAuthAccessToken(at);
			if(content.length()>130){
				content = content.substring(0, 128)+"...";
			}
			
			GeoLocation location = new GeoLocation(latitude, longitude);
			
			result = twitter.updateStatus(content, location).getText();
			
			if(result.equals(content)){
				
				result = TravlogVars.SUCCESS;
			}
			System.out.println("@@@@@@@@@@트위터 포스팅 결과 location :@@@@"+result);
			

		}  catch (TwitterException e) {
			return result;
		}
		
		return result;
	}

	public String follow(String tokenPare, String targetId) {
		
		String result = TravlogVars.FAIL;
		
		Twitter twitter = new TwitterFactory().getInstance();
		
		twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
		
		
		String accessToken = tokenPare.substring(0, tokenPare.indexOf("@"));
		String accessTokenSecret = tokenPare.substring(tokenPare.indexOf("@")+1);
		AccessToken at = new AccessToken(accessToken,accessTokenSecret);
		twitter.setOAuthAccessToken(at);
	
		
		try{
			twitter.createFriendship(targetId, true);
			result = TravlogVars.SUCCESS;
		}catch (TwitterException e){
			return result;
		}
		
		return result;
	}
	
	public ArrayList<Integer> getMyFollowersList(String tokenPare){
		String result = TravlogVars.FAIL;
		ArrayList<Integer> list = new ArrayList<Integer>();
		Twitter twitter = new TwitterFactory().getInstance();
		
		twitter.setOAuthConsumer(TravlogVars.twitterConsumerKey, TravlogVars.twitterConsumersecret);
		
		String accessToken = tokenPare.substring(0, tokenPare.indexOf("@"));
		String accessTokenSecret = tokenPare.substring(tokenPare.indexOf("@")+1);
		AccessToken at = new AccessToken(accessToken,accessTokenSecret);
		twitter.setOAuthAccessToken(at);
	
		try{
			IDs ids = twitter.getFriendsIDs();
			for(int i = 0; i<ids.getIDs().length;i++){
				list.add(ids.getIDs()[i]);
			}
			
		}catch (TwitterException e){
			return null;
		}
		return list;
	}
}
